const { excsql } = require('../database/mysql')
const xss = require('xss')
const getList = (author, keyword) => {
  let sql = `select *from blogs where 1=1 ` //预防where 1=1 这个是防止传入参数为空导致sql语句报错
  if (author) {
    sql += `and author='${author}' `

  }
  if (keyword) {
    sql += `and title like '%${keyword}%' `
  }
  sql += `order by createtime desc;`//倒叙排列
  return excsql(sql) //promise对象
}
const getDetail = (id) => {
  const sql = `select * from blogs where id='${id}'`
  return excsql(sql).then((rows) => {
    return rows[0]
  })
}
const newBlog = (blogData = {}) => {  //创建一个博客所对应的方法
  const title = xss(blogData.title)
  const content = xss(blogData.content)
  const author = blogData.author
  const createtime = Date.now()
  const sql = `insert into blogs (title,content,createtime,author) values ('${title}', '${content}', ${createtime},'${author}')`
  return excsql(sql).then(insertData => {
    console.log(insertData);
    return {
      id: insertData.insertId//这个东西是我插入到数据库后，会自动生成的一个数据
    }
  })
}
const updateBlog = (id, blogData = {}) => {
  const title = blogData.title
  const content = blogData.content
  const sql = `update blogs set title='${title}', content='${content}' where id=${id}`

  return excsql(sql).then(updateData => {

    if (updateData.affectedRows > 0) {
      return true
    }
    return false
  })
}
const deleteBlog = (id, author) => {
  const sql = `delete from blogs where id='${id}' and author='${author}'`
  return excsql(sql).then(deleteData => {

    if (deleteData.affectedRows > 0) {
      return true
    }
    return false
  })
}



module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  deleteBlog
}